package com.dd.census.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.dd.census.entity.Dictionary;
import com.dd.census.mapper.DictionaryMapper;


public class DictCache {
	@Autowired
	private static DictionaryMapper dictionaryMapper;

	public static Map<String, List<Dictionary>> cache = new HashMap<String, List<Dictionary>>();

    static {
        //注意此处不能使用依赖注入，因为此时dictionariesRepository还没创建出来，可以获取上下文手动创建
    	dictionaryMapper = SpringUtils.getBean(DictionaryMapper.class);
    	toData();
    }

    public static void toData(){
    	Dictionary dic = new Dictionary();
        List<Dictionary> all = dictionaryMapper.selectAll(dic);
        cache = all.stream().collect(Collectors.groupingBy(Dictionary::getGroupName));
    }
    
    /** 返回list数据格式 */
    public static List<Dictionary> toDataList(String findType){
        List<Dictionary> dictionariesList = cache.get(findType);
        if(CollectionUtils.isEmpty(dictionariesList)){
            return new ArrayList<Dictionary>();
        }
        return cache.get(findType);
    }
    
    /** 返回map数据格式  */
    public static Map<String, String> toDataMap(String findType){
        List<Dictionary> dictionariesList = toDataList(findType);
        return dictionariesList.stream().collect(Collectors.toMap(Dictionary::getGroupName, Dictionary::getValue, (a, b) -> b));
    }
}
